Imports System
Imports NUnit.Framework
Imports ValidationFramework
Imports ValidationFramework.Reflection


Public Class TypeCacheExample
#Region "Example"
    Public Class Car

        Private _numberOfDoors As Integer

        ' Assume for the purposes of this sample that cars can have between 2 and 5 doors.
        Public Property NumberOfDoors() As Integer
            Get
                Return _numberOfDoors
            End Get
            Set(ByVal value As Integer)
                _numberOfDoors = value
            End Set
        End Property


    End Class


    <TestFixture()> _
    Public Class ExampleUsage

        <Test()> _
        Public Sub Run()

            Dim car As New Car

            ' Create a PropertyValidationManager for Car
            Dim manager As New PropertyValidationManager(car)
            Assert.IsTrue(manager.IsValid)

            Dim carType As Type = GetType(Car)

            Dim rangeRule As New RangeRule(Of Integer)(Nothing, False, 2, 5, True, _
            True)

            Dim typeDescriptor As TypeDescriptor = TypeCache.GetType(carType.TypeHandle)
            ' create a PropertyDescriptor for NumberOfDoors and add a RangeRule to it.  
            Dim propertyDescriptor As PropertyDescriptor = _
            typeDescriptor.GetOrCreatePropertyDescriptor("NumberOfDoors")
            propertyDescriptor.Rules.Add(rangeRule, Nothing)

            ' 0 is an invalid NumberOfDoors 
            manager.ValidateAll()

            Assert.IsFalse(manager.IsValid)

            ' 1 is an invalid NumberOfDoors 
            car.NumberOfDoors = 1
            manager.ValidateAll()
            Assert.IsFalse(manager.IsValid)

            car.NumberOfDoors = 2
            manager.ValidateAll()
            Assert.IsTrue(manager.IsValid)

            ' 6 is an invalid NumberOfDoors 
            car.NumberOfDoors = 6
            manager.ValidateAll()
            Assert.IsFalse(manager.IsValid)

            ' clear the rule
            propertyDescriptor.Rules.Clear()

            ' 6 is now a valid NumberOfDoors because the validation rule has been removed.
            ' use TryValidateAllProperties. Since there are no rules ValidateAllProperties 
            ' would throw an exception. 
            manager.TryValidateAll()
            Assert.IsTrue(manager.IsValid)
        End Sub

    End Class


#End Region
End Class